package com.stanyung.realtimeserver;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.stanyung.realtimeserver.codec.ChatProtocolDecoder;
import com.stanyung.realtimeserver.codec.Packet;

public class XServerHandler extends IoHandlerAdapter {
	
	private static final Logger logger = LoggerFactory.getLogger(XServerHandler.class);

	private Map<String, IoSession> sessionMap = Collections.synchronizedMap(new HashMap<String, IoSession>());

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		Packet packet = (Packet) message; 
		logger.debug("messageReceived : " + packet.toString());
		packet = new Packet(5, 6, (byte) 1, (byte)1, "HelloWorld, HelloWorld. HelloWorld, HelloWorld. HelloWorld, HelloWorld. HelloWorld, HelloWorld.");
		session.write(packet);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		Packet packet = (Packet) message; 
		logger.debug("messageSent : " + packet.toString());
		super.messageSent(session, message);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
//		System.out.println("IDLE " + session.getIdleCount(status));
//		session.write(new Packet);
		Packet packet = Packet.newHeartBeatPacket();
		session.write(packet);
	}

}
